import { onActivated, onMounted, onUnmounted, ref } from "vue";
import { throttle } from "underscore";

// 监听window的滚动
export default function useScroll(elRef) {
  let el = window;

  const isReachBottom = ref(false);
  const scrollTop = ref(0);
  const clientHeight = ref(0);
  const scrollHeight = ref(0);

  // const scrollListenerHandler = throttle(() => {
  //   clientHeight.value = document.documentElement.clientHeight; //视口高度
  //   scrollTop.value = document.documentElement.scrollTop; //距离顶部高度
  //   scrollHeight.value = document.documentElement.scrollHeight; // 页面总高/长度
  //   // console.log(clientHeight, Math.ceil(scrollTop), scrollHeight);

  //   if (clientHeight.value + Math.ceil(scrollTop.value) >= scrollHeight.value) {
  //     isReachBottom.value = true;
  //   }
  // }, 100);
  // onMounted(() => {
  //   window.addEventListener("scroll", scrollListenerHandler);
  // });

  // onUnmounted(() => {
  //   window.removeEventListener("scroll", scrollListenerHandler);
  // });

  const scrollListenerHandler = throttle(() => {
    if (el === window) {
      clientHeight.value = document.documentElement.clientHeight;
      scrollTop.value = document.documentElement.scrollTop;
      scrollHeight.value = document.documentElement.scrollHeight;
    } else {
      clientHeight.value = el.clientHeight;
      scrollTop.value = el.scrollTop;
      scrollHeight.value = el.scrollHeight;
    }
    if (
      clientHeight.value + Math.ceil(scrollTop.value) + 1 >=
      scrollHeight.value
    ) {
      isReachBottom.value = true;
    }
  }, 100);

  onMounted(() => {
    if (elRef) el = elRef.value;
    elRef.value.addEventListener("scroll", scrollListenerHandler);
  });

  onUnmounted(() => {
    el.removeEventListener("scroll", scrollListenerHandler);
  });

  return { isReachBottom, scrollTop, clientHeight, scrollHeight };
}
